import {
  getListService,
  addOneService,
  deleteOneService,
} from '@/services/ziyounongji';
import { notiErr } from '@/utils/notification';

const namespace = 'jixieguanli_ziyounongji';
const initialState = {
  list: [
    // {
    //   id: 1,
    //   machineName: '农机名1',
    //   lengthOfUse: 300,
    //   repairCondition: '这是农机1号的维修状况',
    //   time: '2019-03-02',
    // },
  ],
};

export default {
  namespace,

  state: {
    ...initialState,
  },

  effects: {
    * getListEffect(_, { call, put, select }) {
      const token = yield select(({ app }) => app.user.token);
      const response = yield call(getListService, { token });

      if (response && !response.errno && response.data) {
        // 登录成功之后的操作
        const rdata = response.data;
        yield put({
          type: 'getListReducer',
          payload: {
            list: rdata.map(v => ({
              id: v.id,
              machineName: v.machine_name,
              lengthOfUse: v.length_of_use,
              repairCondition: v.repair_condition,
            }))
          },
        });
      } else {
        notiErr(response.errmsg);
      }
    },
    // 添加一条记录
    * addOneRecordEffect({ payload: { data } }, { call, put, select }) {
      const newRecord = {
        machineName: data.machineName,
        lengthOfUse: data.lengthOfUse,
        repairCondition: data.repairCondition,
        // time: timeTransform(Math.floor(Date.now() / 1000), 'YYYY-MM-DD'),
      };

      const token = yield select(({ app }) => app.user.token);
      const response = yield call(addOneService, {
        token,
        ...newRecord,
      });

      if (response && !response.errno && response.data) {
        // 登录成功之后的操作
        const rdata = response.data;
        console.log(response);
        yield put({
          type: 'addOneReducer',
          payload: {
            id: rdata.id,
            ...newRecord,
          },
        });
      } else {
        notiErr(response.errmsg);
      }
    },
    // 删除一条记录
    * deleteOneRecordEffect({ payload: { data } }, { call, put, select }) {
      const token = yield select(({ app }) => app.user.token);
      const response = yield call(deleteOneService, {
        token,
        recordId: data.id,
      });
      if (response && !response.errno) {
        yield put({
          type: 'deleteOneReducer',
          payload: {
            id: data.id,
          },
        });
      } else {
        notiErr(response.errmsg);
      }
    },
  },

  reducers: {
    addOneReducer(state, { payload }) {
      return {
        ...state,
        list: [payload, ...state.list],
      };
    },
    deleteOneReducer(state, { payload }) {
      return {
        ...state,
        list: state.list.filter(v => v.id !== payload.id),
      };
    },
    getListReducer(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    resetDataReducer() {
      return {
        ...initialState,
      };
    },
  },
};
